var express = require('express');
var router = express.Router();
const axios = require('axios');
const iconv = require('iconv-lite');
const cheerio = require('cheerio');
const { getWBTopSearch, getZHTopSearch, getBDTopSearch } = require('../plugin/handleDom')
const multer = require('multer');
const path = require('path');
const { getPublicIPAddress } = require('../plugin/server');
const fs = require('fs');
const { authenticateToken } = require('../plugin/jwt');
// const {port} = require('../bin/www');
// console.log(port);

let address = '';

// 使用函数查询公网IP
getPublicIPAddress((error, ipAddress) => {
    if (error) {
        console.error('Error fetching public IP:', error);
    } else {
        // console.log('Public IP Address:', ipAddress);
        address = ipAddress;
        console.log(address);
    }
});

function getLastDotAndSuffix(inputString) {
    // 使用正则表达式寻找最后一个"."及之后的内容
    const match = inputString.match(/(\.[^.]*)$/);

    // 如果找到匹配项，则返回匹配的结果（即尾缀部分）
    if (match) {
        return match[0];
    } else {
        // 如果没有找到"."，则返回空字符串或者其他默认值
        return '';
    }
}

const storageImg = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../public/file/img'));
    },
    filename: function (req, file, cb) {
        let uniqueID = new Date().getTime() + '_' + Math.random().toString(36).substring(2);
        // 生成一个基于当前日期时间的唯一文件名
        cb(null, `${uniqueID}${getLastDotAndSuffix(file.originalname)}`);
    },
});

const imgUpload = multer({ storage: storageImg });

const storageVideo = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../public/file/video'));
    },
    filename: function (req, file, cb) {
        let uniqueID = new Date().getTime() + '_' + Math.random().toString(36).substring(2);
        // 生成一个基于当前日期时间的唯一文件名
        cb(null, `${uniqueID}${getLastDotAndSuffix(file.originalname)}`);
    },
});

const videoUpload = multer({ storage: storageVideo });

/* GET home page. */
router.post('/uploadImage', authenticateToken, imgUpload.single('image'), async function (req, res, next) {
    try {
        // req.file 是由multer填充的对象，包含已上传文件的信息
        console.log(req.file);
        const file = req.file;

        if (!file) {
            const error = new Error('请上传文件');
            error.httpStatusCode = 400;
            return next(error);
        }

        let data = {
            url: `https://www.ylmlove.site/api/file/img/${file.filename}`
        }

        res.send({ "errno": 0, data });
    } catch (err) {
        next(err);
    }
});

router.post('/uploadVideo', authenticateToken, videoUpload.single('video'), async function (req, res, next) {
    try {
        // req.file 是由multer填充的对象，包含已上传文件的信息
        const file = req.file;

        if (!file) {
            const error = new Error('请上传文件');
            error.httpStatusCode = 400;
            return next(error);
        }

        path.join(__dirname, 'public/file')

        let data = {
            url: `https://www.ylmlove.site/api/file/video/${file.filename}`
        }

        res.send({ "errno": 0, data });
    } catch (err) {
        next(err);
    }
});

module.exports = router;